package com.globalwave.system.web;


import org.dom4j.Element;

import com.globalwave.base.BaseAction;
import com.globalwave.common.ArrayOrderList;
import com.globalwave.common.ArrayPageList;
import com.globalwave.common.Convertor;
import com.globalwave.common.U;
import com.globalwave.system.entity.SessionUser;
import com.globalwave.system.entity.User;
import com.globalwave.system.entity.UserCriterion;
import com.globalwave.system.service.UserService;
import com.globalwave.system.web.annotations.Pid;
import com.opensymphony.xwork2.Preparable;

public class UserAction extends BaseAction implements Preparable {
    
    private static final long serialVersionUID = 182557698841454660L;
    
    private UserService userService = null ;
    
    private User user ;
    private UserCriterion userCriterion ;
    private Long[] organization_ids ;
    private boolean isLoginPos = false ;
    
    public String execute() throws Exception {
        return this.list();    
        
    }

    @Pid(value=101)
    public String list() throws Exception {        
        
        ArrayOrderList order = new ArrayOrderList() ;
        order.addAsc("user_id") ;
        ArrayPageList<User> pageList = userService.query(userCriterion,pageIndex,pageSize,order) ;

        renderXML(pageList.asXML()) ;
        
        return null ;    
        
    }
    
    @Pid(value=102)
    public String create()  throws Exception {        
        /*
        User userToCheck = new User() ;
        userToCheck.setLogin_id(user.getLogin_id()) ;
        if (userService.checkUserExisted(userToCheck)) {

            renderXML(this.getMessage(null,"�û��Ѿ����ڣ�����ʧ�ܣ�").asXML()) ;
            return null ;
        }
        
        user.setPassword_(Util.hash(user.getPassword_())) ;
         */
        
        Object newUser = userService.create(user,organization_ids) ;

        
        renderXML(this.getSuccessCreateMessage(newUser).asXML()) ;
        
        return null;    
        
    }
    
    @Pid(value=103)
    public String update()  throws Exception {     

    	/*
        if (StringUtils.isEmpty(user.getPassword_())) {
            user.addExclusions("password_") ;
            // user.setPassword_(userService.find(user.getUser_id()).getPassword_()) ;            
        } else {
            user.setPassword_(Util.hash(user.getPassword_())) ;
        }*/
        
        userService.update(user,organization_ids) ;

        renderXML(this.getSuccessUpdateMessage(user).asXML()) ;
        
        return null;    
        
    }

    @Pid(value=104)
    public String delete()  throws Exception {
        
        if (ids == null) {
            userService.delete(user) ;
        } else {
            userService.deleteAll(ids) ;
        }

        renderXML(this.getSuccessDeleteMessage().asXML()) ;
        
        return null;    
        
    }


    public String changePassword() throws Exception {
    	
    	userService.changePassword(user) ;

        renderXML(this.getMessage(null, "成功更改密码！").asXML()) ;
        
        return null; 
    }
    
    /*
    public String checkUserExisted() throws Exception {
        renderText(userService.checkUserExisted(user)+"") ;
        return null ;
    }*/
    
    public void prepare() throws Exception {
        // TODO Auto-generated method stub

    }
    

    @SuppressWarnings("unchecked")
    @Pid(value=Pid.DO_NOT_CHECK)
    public String login() throws Exception {
    	/*
        if (StringUtils.isBlank(this.user.getLogin_id()) 
                || StringUtils.isBlank(this.user.getPassword_())) {
            this.renderXML(this.getMessage(null, this.getText("error.nullerror")).asXML()) ;
            //this.addActionError(this.getText("error.nullerror"));
            return null;
        }

        SessionUser sessionUser = null ;
        User user = this.userService.findByLoginId(this.user.getLogin_id());
        if (user == null) {
            this.renderXML(this.getMessage(null, this.getText("error.user.notexist")).asXML()) ;
            return null;
        } else {
            sessionUser = new SessionUser() ;
            sessionUser.setUser(user) ;
        }
        /*
        if (this.getSysConfig().isUseSafeLogin()) {
            if (this.getLoginErrorService().isCanNotLogin(ui.getId())) {
                this.addActionError(this.getText("error.login.times"));
                return INPUT;
            }
        }* /

        if (!Util.hash(this.user.getPassword_()).equals(user.getPassword_())) { // �������
            this.renderXML(this.getMessage(null, this.getText("error.login.passwd")).asXML()) ;
            /*
            if (this.getSysConfig().isUseSafeLogin()) {
                try {
                    this.getLoginErrorService().createLoginError(ui.getId());
                } catch (BbscsException ex1) {
                    logger.error(ex1);
                }
            }* /
            //this.addActionError(this.getText("error.login.passwd"));
            return null;
        }
        
        ArrayPageList<Privilege> privileges =
            privilegeService.getAllByUserId(user.getUser_id()) ;
        
        Set<Short> privilegeIds = new HashSet<Short>(privileges.size()) ;
        for (int i = privileges.size() - 1 ; i >= 0 ; i --) {
            privilegeIds.add(privileges.get(i).getCode_()) ;
        }
        sessionUser.setPrivilege_ids(privilegeIds) ;*/

    	String isPos = getRequest().getParameter("isLoginPos") ;
    	if (isPos == null) {
    		this.isLoginPos = false ;
    	} else {
    		this.isLoginPos = Boolean.parseBoolean(isPos) ;
    	}
        SessionUser sessionUser = this.userService.login(this.user, isLoginPos) ;
        
        this.getSession().setAttribute(SessionUser.SESSION_PK, sessionUser);
                
        Element root = sessionUser.toXML() ;
        Convertor.addProperty(root, "system_date", U.currentDate()) ;
        renderXML(root.asXML()) ;
        
/*
        if (this.getSysConfig().isUseAuthCode()) {
            String cauthCode = this.getUserCookie().getAuthCode();

            if (StringUtils.isBlank(cauthCode) || !cauthCode.equals(this.getAuthCode())) {
                this.addActionError(this.getText("error.login.authcode"));
                return INPUT;
            }
        }

        ui.setLastLoginIP(ui.getLoginIP());
        ui.setLastLoginTime(ui.getLoginTime());

        ui.setLoginIP(this.getRemoteAddr());
        ui.setLoginTime(new Date());
        ui.setUserLocale(this.getLocale().toString());

        long nowTime = System.currentTimeMillis();
        UserOnline uo = new UserOnline();
        uo.setAtPlace("");
        uo.setBoardID(0);
        uo.setNickName(ui.getNickName());
        uo.setOnlineTime(nowTime);
        uo.setUserGroupID(ui.getGroupID());
        uo.setUserID(ui.getId());
        uo.setUserName(ui.getUserName());
        uo.setValidateCode(ui.getId() + "_" + nowTime);
        if (this.getHiddenLogin() == 1 || ui.getHiddenLogin() == 1) { // �û������¼
            uo.setHiddenUser(1);
        }

        try {
            ui = this.getUserService().saveAtLogin(ui); // �û���¼����
            uo = this.getUserOnlineService().createUserOnline(uo); // ���������û���
        } catch (BbscsException ex) {
            logger.error(ex);
            return INPUT;
        }

        UserSession us = userService.getUserSession(ui);
        us.setValidateCode(uo.getValidateCode());
        // this.getUserSessionCache().add(ui.getUserName(), us);
        this.getSession().put(Constant.USER_SESSION_KEY, us);

        this.getUserCookie().removeAuthCode();
        this.getUserCookie().addCookies(ui);
        // this.getUserCookie().addValidateCode(uo.getValidateCode());
        if (this.getCookieTime() != -1) {
            this.getUserCookie().addC("U", this.getUsername(), this.getCookieTime());
            this.getUserCookie().addDES("P", Util.hash(this.getPasswd()), this.getCookieTime());
        }*/

        return null;
    }

    public String cookieLogin() {
        /*
        UserInfo ui = this.getUserService().findUserInfoByUserName(this.getUserCookie().getUserName());
        if (ui == null) {
            this.addActionError(this.getText("error.user.notexist"));
            return INPUT;
        }

        if (!this.getUserCookie().getPasswd().equals(ui.getRePasswd())) { // �������
            if (this.getSysConfig().isUseSafeLogin()) {
                try {
                    this.getLoginErrorService().createLoginError(ui.getId());
                } catch (BbscsException ex1) {
                    logger.error(ex1);
                }
            }
            this.addActionError(this.getText("error.login.passwd"));
            return INPUT;
        }

        ui.setLastLoginIP(ui.getLoginIP());
        ui.setLastLoginTime(ui.getLoginTime());

        ui.setLoginIP(this.getRemoteAddr());
        ui.setLoginTime(new Date());
        ui.setUserLocale(this.getLocale().toString());

        long nowTime = System.currentTimeMillis();
        UserOnline uo = new UserOnline();
        uo.setAtPlace("");
        uo.setBoardID(0);
        uo.setNickName(ui.getNickName());
        uo.setOnlineTime(nowTime);
        uo.setUserGroupID(ui.getGroupID());
        uo.setUserID(ui.getId());
        uo.setUserName(ui.getUserName());
        uo.setValidateCode(ui.getId() + "_" + nowTime);
        if (this.getHiddenLogin() == 1 || ui.getHiddenLogin() == 1) { // �û������¼
            uo.setHiddenUser(1);
        }

        try {
            ui = this.getUserService().saveAtLogin(ui); // �û���¼����
            uo = this.getUserOnlineService().createUserOnline(uo); // ���������û���
        } catch (BbscsException ex) {
            logger.error(ex);
            return INPUT;
        }

        UserSession us = userService.getUserSession(ui);
        us.setValidateCode(uo.getValidateCode());
        this.getSession().put(Constant.USER_SESSION_KEY, us);

        this.getUserCookie().removeAuthCode();
        this.getUserCookie().addCookies(ui);

        if (Constant.USE_URL_REWRITE) {
            tourl = this.getBasePath() + "main.html";
        } else {
            tourl = this.getBasePath() + BBSCSUtil.getActionMappingURLWithoutPrefix("main");
        }

        return SUCCESS;*/
        return null;
    }
    
    // ------------------------------------------------------------------------
    
    // ioc
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    // entity...
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public UserCriterion getUserCriterion() {
        return userCriterion;
    }

    public void setUserCriterion(UserCriterion userCriterion) {
        this.userCriterion = userCriterion;
    }

    public Long[] getOrganization_ids() {
        return organization_ids;
    }

    public void setOrganization_ids(Long[] organization_ids) {
        this.organization_ids = organization_ids;
    }


}
